<template>
  <div class="custom-tablePage-container">
    <div class="screen-conditions-container">
      <ScreenConditions :isDataType="false">
        <template slot="conditions">
          <a-select placeholder="请选择专业" v-model="condition.major">
            <a-select-option
              :value="item.dicItemCode"
              v-for="item in majorSource"
              :key="item.dicItemCode"
            >
              {{ item.dicItemName }}
            </a-select-option>
          </a-select>
          <a-select placeholder="请选择状态" v-model="condition.approveStatus">
            <a-select-option value="0">
              待提交
            </a-select-option>
            <a-select-option value="1">
              审批中
            </a-select-option>
            <a-select-option value="2">
              审批完成
            </a-select-option>
            <a-select-option value="3">
              驳回
            </a-select-option>
          </a-select>
          <a-range-picker
            v-if="pageModule != 2"
            :placeholder="['提交开始日期', '提交结束日期']"
            format="YYYY-MM-DD HH:mm:ss"
            valueFormat="YYYY-MM-DD HH:mm:ss"
            v-model="condition.date"
            :show-time="{
              hideDisabledOptions: true,
              defaultValue: [
                moment('00:00:00', 'HH:mm:ss'),
                moment('11:59:59', 'HH:mm:ss'),
              ],
            }"
          />
        </template>
        <template slot="operate">
          <a-button class="cu-btn-primary" icon="search" @click="search()">
            查询
          </a-button>
          <a-button class="cu-btn-filter" icon="reload" @click="reset()">
            重置
          </a-button>
        </template>
      </ScreenConditions>
    </div>
    <div class="table-body-container">
      <div class="table-operate ">
        <a-button
          @click="handleWrapPage({}, 1)"
          class="cu-btn-primary margin-bottom-xs"
          icon="plus"
          v-action="'table_add_' + pageModule"
        >
          新增
        </a-button>
      </div>
      <div class="table-main">
        <vxe-table
          ref="xTable"
          height="99%"
          align="left"
          show-overflow
          show-header-overflow
          border="inner"
          :data="tableData"
          :column-config="{ resizable: true }"
          size="small"
          :loading="loading"
          :row-config="{ keyField: 'uuid' }"
          :expand-config="{
            reserve: true,
            visibleMethod: visibleMethod,
          }"
        >
          <!-- 历史版本 -->
          <vxe-column type="expand" width="26">
            <template #content="{ row }">
              <div class="expand-wrapper">
                <vxe-table
                  align="center"
                  border="inner"
                  :data="row.historys || []"
                  :column-config="{ resizable: true }"
                  show-overflow
                  show-header-overflow
                  size="small"
                >
                  <vxe-column field="versionNumber" title="版本号">
                  </vxe-column>
                  <vxe-column field="majorDesc" title="专业"> </vxe-column>
                  <!-- 竣工设计字段 -->
                  <vxe-column
                    field="sectionDesc"
                    title="分项工程"
                    v-if="pageModule == 8"
                  >
                    <template #default="{ row }">
                      {{ row.sectionDesc || row.section }}
                    </template>
                  </vxe-column>
                  <vxe-column
                    :field="item.key"
                    :title="item.title"
                    v-for="(item, index) in columns"
                    :key="index"
                  >
                    <template #default="{ row }">
                      <div class="files-icon">
                        <a-tooltip placement="top">
                          <template slot="title"> 预览 </template>
                          <a-icon
                            type="eye"
                            class="preview-btn"
                            :class="[
                              isEmptyObject(row.map[item.key]) && 'disabled',
                            ]"
                            @click="
                              handelFileModal(row.map[item.key], item, row)
                            "
                          />
                        </a-tooltip>
                        <a-tooltip
                          placement="top"
                          v-action="'down_load_' + pageModule"
                        >
                          <template slot="title">
                            下载
                          </template>
                          <a-icon
                            v-if="
                              row.map[item.key]
                                ? row.map[item.key]['downloadStatus']
                                : false
                            "
                            type="sync"
                            spin
                          />
                          <a-icon
                            v-else
                            type="download"
                            class="download-btn"
                            :class="[
                              isEmptyObject(row.map[item.key]) && 'disabled',
                            ]"
                            @click="
                              downloadFile(
                                row.map[item.key],
                                item,
                                row,
                                item.key,
                                'history'
                              )
                            "
                          />
                        </a-tooltip>
                      </div>
                    </template>
                  </vxe-column>
                  <vxe-column field="reason" title="驳回原因"> </vxe-column>
                  <vxe-column
                    field="operate"
                    width="80"
                    title="操作"
                    fixed="right"
                    align="left"
                  >
                    <template #default="{ row }">
                      <div class="text-button-group">
                        <!-- 详情 -->
                        <a-tooltip placement="top">
                          <template slot="title">
                            查看
                          </template>
                          <a-icon
                            type="file-search"
                            @click="handleWrapPage(row, 3)"
                          />
                        </a-tooltip>
                      </div>
                    </template>
                  </vxe-column>
                </vxe-table>
              </div>
            </template>
          </vxe-column>
          <vxe-column
            type="seq"
            width="50"
            title="序号"
            align="center"
          ></vxe-column>
          <vxe-column field="majorDesc" title="专业"> </vxe-column>
          <!-- 竣工设计字段 -->
          <vxe-column
            field="sectionDesc"
            title="分项工程"
            v-if="pageModule == 8"
          >
          </vxe-column>
          <!--  -->
          <vxe-column
            :field="item.key"
            :title="item.title"
            v-for="(item, index) in columns"
            :key="index"
          >
            <template #default="{ row}">
              <div class="files-icon">
                <a-tooltip placement="top">
                  <template slot="title"> 预览</template>
                  <a-icon
                    type="eye"
                    class="preview-btn"
                    :class="[isEmptyObject(row[item.key]) && 'disabled']"
                    @click="handelFileModal(row[item.key], item, row)"
                  />
                </a-tooltip>
                <a-tooltip placement="top" v-action="'down_load_' + pageModule">
                  <template slot="title">
                    下载
                  </template>
                  <a-icon
                    v-if="
                      row[item.key] ? row[item.key]['downloadStatus'] : false
                    "
                    type="sync"
                    spin
                  />
                  <!-- :class="[isEmptyObject(row[item.key]) && 'disabled']" -->
                  <a-icon
                    v-else
                    type="download"
                    class="download-btn"
                    :class="[isEmptyObject(row[item.key]) && 'disabled']"
                    @click="downloadFile(row[item.key], item, row, item.key)"
                  />
                </a-tooltip>
              </div>
            </template>
          </vxe-column>

          <!--  -->
          <!-- <vxe-column
            field="nodeDesc"
            title="当前节点"
            fixed="right"
            v-if="[2, 3, 4].includes(pageModule)"
          >
            <template #default="{ row }">
              <span style="color:#1677ff">{{ row.nodeDesc }}</span>
            </template>
          </vxe-column> -->
          <!--  -->
          <vxe-column title="状态" fixed="right">
            <template #default="{ row }">
              <div class="state" :class="[filterStateClass(row.approveStatus)]">
                <span v-if="[2, 3, 4].includes(pageModule)">
                  {{ row.nodeDesc }}
                </span>
                <span v-else>
                  {{ filterStateName(row.approveStatus) }}
                </span>
              </div>
            </template>
          </vxe-column>
          <template v-if="pageModule != 2">
            <vxe-column field="creator" title="提交人" fixed="right">
            </vxe-column>
            <vxe-column field="createTimeStr" title="提交时间" fixed="right">
            </vxe-column>
          </template>
          <vxe-column
            field="operate"
            width="180"
            title="操作"
            fixed="right"
            align="left"
          >
            <template #default="{ row }">
              <div class="text-button-group">
                <!-- 提交 -->
                <a-tooltip placement="top" v-if="row.submit">
                  <template slot="title">
                    提交
                  </template>
                  <icon-fonts
                    icon="icon-fabu-tijiao-tijiaobanben"
                    class="submit"
                    @change="handleSubmit(row)"
                  ></icon-fonts>
                </a-tooltip>
                <!-- 审批 -->
                <a-tooltip placement="top" v-if="row.approve">
                  <template slot="title">
                    审批
                  </template>
                  <icon-fonts
                    icon="icon-shenpi1"
                    class="approve"
                    @change="handleWrapPage(row, 4)"
                  ></icon-fonts>
                </a-tooltip>
                <!-- 审批记录 -->
                <a-tooltip placement="top" v-if="row.approveRecord">
                  <template slot="title">
                    审批记录
                  </template>
                  <icon-fonts
                    icon="icon-shenpi"
                    class="record"
                    @change="gotoApprovalRecord(row)"
                  ></icon-fonts>
                </a-tooltip>
                <!-- 详情 -->
                <a-tooltip placement="top">
                  <template slot="title">
                    查看
                  </template>
                  <a-icon type="file-search" @click="handleWrapPage(row, 3)" />
                </a-tooltip>
                <!-- 编辑 -->
                <a-tooltip
                  placement="top"
                  v-action="'table_edit_' + pageModule"
                  v-if="row.edit"
                >
                  <template slot="title">
                    编辑
                  </template>
                  <a-icon
                    type="edit"
                    class="edit-btn"
                    @click="handleWrapPage(row, 2)"
                  />
                </a-tooltip>
                <!-- 删除 -->
                <a-tooltip v-if="row.del">
                  <template slot="title">
                    删除
                  </template>
                  <a-icon type="delete" @click="handleDelClick(row)" />
                </a-tooltip>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="table-pager"></div>
    </div>
    <!-- 查看附件 -->
    <viewFileModal
      :visible.sync="viewFileModal.visible"
      :fileList="viewFileModal.fileList"
      :classifyId="viewFileModal.classifyId"
      :uuid="viewFileModal.uuid"
      :subtitle="viewFileModal.name"
    ></viewFileModal>
    <!-- 新增/编辑/查看/审批 -->
    <wrapPage
      :key="wrapPage.key"
      :visible.sync="wrapPage.visible"
      :parameter="wrapPage.row"
      :pageOperate="wrapPage.operate"
      @close="closePage()"
    ></wrapPage>
    <!-- 审批记录 -->
    <comment-modal ref="commentModal"></comment-modal>
    <!-- 单文件预览弹窗 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>
    <!--  目录+文件预览 -->
    <treeViewFileModal
      :visible.sync="treeViewFileModal.visible"
      :subtitle="treeViewFileModal.name"
      :dataSource="treeViewFileModal.source"
    ></treeViewFileModal>
  </div>
</template>

<script>
import moment from "moment";
import { mapGetters } from "vuex";
import { axios } from "@/utils/request";
import { _getUUID } from "@/utils/util.js";
import { downLoadBatchFileByArraybuffer, getToken } from "@/utils/TopVUI";
import ScreenConditions from "@/components/extendCustom/ScreenConditions";
//审批记录
import commentModal from "@/pages/workflow/oaLeave/comment.vue";
//新增
import wrapPage from "./wrapPage.vue";
//预览
import viewFileModal from "./viewFileModal.vue";
//单文件预览
import previewModal from "@/pages/document/minio/previewModal";
//目录+文件预览
import treeViewFileModal from "./treeViewFileModal.vue";
import { getDicItemByCode } from "@/api/common.js";
export default {
  provide() {
    return {
      moduleSource: () => this.pageModule,
    };
  },
  props: {
    pageModule: {
      type: [Number, String],
      default: 1,
    },
  },
  components: {
    ScreenConditions,
    viewFileModal,
    wrapPage,
    commentModal,
    previewModal,
    treeViewFileModal,
  },
  data() {
    return {
      //查询体条件
      condition: {
        //专业
        major: undefined,
        //状态
        approveStatus: undefined,
        //日期范围
        date: [],
      },
      //专业
      majorSource: [],
      //列表
      loading: false,
      tableData: [],
      pager: {
        page: 1,
        pageSize: 50,
        total: 0,
      },
      columns: [],
      //查看附件
      viewFileModal: {
        classifyId: "",
        uuid: "",
        name: "",
        visible: false,
        fileList: [],
      },
      // 新增/编辑/查看
      wrapPage: {
        visible: false,
        key: _getUUID(),
        row: {},
        operate: 1,
      },
      //单文件预览
      previewModal: {
        visible: false,
        loading: false,
      },
      //目录+文件预览
      treeViewFileModal: {
        visible: false,
        name: "",
        source: {},
      },
    };
  },
  computed: {
    ...mapGetters(["configData", "userInfo"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
  },
  mounted() {
    this.getData();
  },
  methods: {
    moment,
    //是否是空对象
    isEmptyObject(obj = {}) {
      let { fileIdInfo } = obj;
      //   console.log(obj, "登录跳转首页出错,这个错误从哪里来的");
      //   if (fileIdInfo && fileIdInfo.length > 0) {
      //     return false;
      //   } else {
      //     return true;
      //   }
      //   console.log(Object.keys(obj), "登录跳转首页出错,这个错误从哪里来的");
      if (Object.keys(obj).length == 0) {
        return true;
      } else if (obj?.fileIdInfo.length == 0) {
        return true;
      } else {
        return false;
      }
    },
    visibleMethod({ row }) {
      if (row.historys && row.historys.length != 0) {
        return true;
      } else {
        return false;
      }
    },
    async getData() {
      //专业
      this.majorSource = await this.getDicCodeData("major");
      await this.getColumnsHeader();
      await this.getTableData();
    },
    //查询字典表
    getDicCodeData(dicCode = "") {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: dicCode })
          .then((res) => {
            let { data } = res;
            resolve(data);
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },

    //查询表头
    getColumnsHeader() {
      let { major = "", approveStatus = "", date } = this.condition;
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/probusiness/schemeDesign/getTableHead`,
            {
              type: this.pageModule,
              major,
              approveStatus,
              startTimeSub: date?.[0] ?? "",
              endTimeSub: date?.[1] ?? "",
            },
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            let source = res?.data ?? [];
            this.columns = [];
            source.forEach((v) => {
              this.columns.push({
                key: v.key,
                title: v.name,
                width: 100,
              });
            });
            resolve();
          })
          .catch((_) => {
            this.columns = [];
            reject();
          });
      });
    },
    //分页列表
    getTableData() {
      let { major = "", approveStatus = "", date } = this.condition;
      let { page, pageSize } = this.pager;
      this.loading = true;
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/probusiness/schemeDesign/getPageSet?pageNo=${page}&pageSize=${pageSize}`,
            {
              type: this.pageModule,
              major,
              approveStatus,
              startTimeSub: date?.[0] ?? "",
              endTimeSub: date?.[1] ?? "",
            },
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            let { data } = res;
            this.tableData = data?.rows ?? [];
            this.pager.total = data?.totalCount ?? 0;
            resolve();
          })
          .catch((_) => {
            this.tableData = [];
            this.pager.total = 0;
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },
    //搜索
    async search() {
      this.pager.page = 1;
      await this.getColumnsHeader();
      await this.getTableData();
    },
    //关闭
    async closePage() {
      this.columns = [];
      this.tableData = [];
      this.getColumnsHeader().finally((_) => {
        this.getTableData();
      });
    },

    //重置
    reset() {
      this.condition.major = undefined;
      this.condition.approveStatus = undefined;
      this.condition.date = [];

      this.search();
    },
    //预览
    handelFileModal(file, item, row) {
      let { fileIdInfo = [], classifyId } = file;
      if (fileIdInfo.length == 0) {
        return;
      } else if (fileIdInfo.length == 1) {
        let fileItem = fileIdInfo?.[0] ?? {};
        this.viewFile(fileItem);
      } else {
        if (classifyId) {
          this.treeViewFileModal.name = item.title;
          this.treeViewFileModal.source = { classifyId, uuid: row.uuid };
          this.treeViewFileModal.visible = true;
        } else {
          this.viewFileModal.name = item.title;
          this.viewFileModal.uuid = row.uuid;
          this.viewFileModal.classifyId = classifyId;
          this.viewFileModal.fileList = fileIdInfo ?? [];
          this.viewFileModal.visible = true;
        }
      }
    },
    //下载
    downloadFile(file, item, row, key, type) {
      let { classifyId, fileIdInfo = [] } = file;
      let { title } = item;
      if (fileIdInfo.length == 0) {
        return;
      }
      if (type == "history") {
        row.map[key].downloadStatus = true;
      } else {
        row[key].downloadStatus = true;
      }
      axios
        .post(
          `/probusiness/schemeDesign/exportZip?classifyId=${classifyId}&uuid=${row.uuid}`,
          {},
          {
            headers: {
              "Content-Type": "application/json",
            },
            apiType: "file",
            responseType: "arraybuffer",
          }
        )
        .then((data) => {
          downLoadBatchFileByArraybuffer(data, title);
        })
        .catch()
        .finally((_) => {
          if (type == "history") {
            row.map[key].downloadStatus = false;
          } else {
            row[key].downloadStatus = false;
          }
        });
    },

    //预览
    viewFile(file) {
      let { previewWay, fileName, url, uuid, unit, bimCadFile } = file;
      let domain = location.origin;
      switch (previewWay) {
        //cad预览
        case "cad":
          window.open(
            `${domain}/#/blackHole/previewCad?uuid=${uuid}&fileName=${fileName}&unit=${unit}`
          );
          return;
        // 模型预览
        case "model":
          let { bhDataSetId } = bimCadFile || {};
          bhDataSetId &&
            window.open(
              `${domain}/#/blackHole/viewDataSetSingleSimple?dataSetId=${bhDataSetId}&name=${fileName}`
            );
          return;
        // 普通文件预览
        case "kkview":
          this.previewModal.loading = true;
          this.$refs.previewModal.type = "file";
          this.$refs.previewModal.fileUrl =
            this.kkFileView +
            "/onlinePreview?url=" +
            encodeURIComponent(Base64.encode(url)) +
            "&watermarkTxt=" +
            //水印内容
            encodeURIComponent("") +
            "&token=" +
            getToken();
          this.previewModal.visible = true;
          this.previewModal.loading = false;
          return;
        default:
          break;
      }
    },

    // 新增/编辑/查看/审批
    handleWrapPage(row, operate) {
      this.wrapPage.operate = operate;
      this.wrapPage.row = row;
      this.wrapPage.key = _getUUID();
      this.wrapPage.visible = true;
    },

    //删除
    handleDelClick(row) {
      let dataLength = this.tableData.length;
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          axios
            .post(
              `/probusiness/schemeDesign/deleteData?uuid=${row.uuid}`,
              {},
              {
                headers: {
                  "Content-Type": "application/json",
                },
              }
            )
            .then(async (res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("删除成功", 1.5);
                if (dataLength == 1 && that.pager.page > 1) {
                  that.pager.page -= 1;
                }
                await that.getColumnsHeader();
                await that.getTableData();
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {});
        },
      });
    },

    //提交
    handleSubmit(row) {
      let that = this;
      const h = this.$createElement;
      this.$confirm({
        title: "您确定提交所选内容?",
        content: "",
        okText: "确定",
        okType: "primary",
        cancelText: "取消",
        centered: true,
        icon: () =>
          h("a-icon", {
            props: {
              type: "question-circle",
              theme: "filled",
            },
            style: "color:#FAAD14",
          }),
        onOk() {
          that.loading = true;
          axios
            .post(
              `/probusiness/schemeDesign/submitData?uuid=${row.uuid}`,
              {},
              {
                headers: {
                  "Content-Type": "application/json",
                },
              }
            )
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("提交成功", 1.5);
                that.loading = true;
                that.getTableData();
              } else {
                that.$message.error(res?.message ?? "提交失败");
              }
            })
            .catch((_) => {
              that.$message.error(res?.message ?? "提交失败");
            })
            .finally(() => {
              that.loading = false;
            });
        },
        onCancel() {},
      });
    },

    //审批记录
    gotoApprovalRecord(record) {
      this.$refs.commentModal.getCommentList(record.uuid);
    },

    filterStateName(val) {
      switch (val) {
        case 0:
          return "待提交";
        case 1:
          return "审批中";
        case 2:
          return "审批通过";
        case 3:
          return "驳回";
        default:
          return "-";
      }
    },

    filterStateClass(val) {
      switch (val) {
        case 0:
          return "default";
        case 1:
          return "ing";
        case 2:
          return "lock";
        case 3:
          return "error";
        default:
          return "";
      }
    },
  },
};
</script>

<style lang="less" scoped>
.custom-tablePage-container {
  width: 100%;
  .expand-wrapper {
    padding: 10px;
    box-sizing: border-box;
  }
  .state {
    &::before {
      position: relative;
      display: inline-block;
      content: "";
      width: 8px;
      height: 8px;
      background: #239b53;
      border-radius: 0px 0px 0px 0px;
      border-radius: 50%;
      margin-right: 10px;
    }
    &.default {
      &::before {
        background: #8c8c8c;
      }
    }
    &.ing {
      &::before {
        background: #f07f17;
      }
    }
    &.lock {
      &::before {
        background: #239b53;
      }
    }

    &.error {
      &::before {
        background: #ff3f4a;
      }
    }
  }
}
</style>
